import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/share_bottom_sheet.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/http/global.dart';
import 'package:tender_flutter/page/home/api/api_collection.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/model/tender_detail_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/regex_util.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/share.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/icon_text_view.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/part_refresh_widget.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

class TenderDetailPage extends StatefulWidget {
  @override
  _TenderDetailPageState createState() => _TenderDetailPageState();
}

class _TenderDetailPageState extends State<TenderDetailPage> {
  // WebViewController _controller;
  // double _height = 100;
  // double _width = ScreenAdapter.screenWidth();

  Future _detailFuture;

  /// 用于更新收藏按钮
  GlobalKey<PartRefreshWidgetState> _collectKey = GlobalKey();

  LoadState _loadState = LoadState.State_Loading;

  /// 标讯id（传递方式获取）
  String tenderId;

  /// 标讯详情
  TenderDetailEntity _detailEntity;

  /// 收藏/取消
  /// 返回是否请求成功的状态
  Future<bool> _setCollection() async {
    var response =
        await ApiCollection.tenderCollection(tenderId: int.parse(tenderId));
    ToastUtils.show(response.msg);
    return response.status == Status.SUCCESS ? true : false;
  }

  /// 获取数据
  Future<ApiResponse<TenderDetailEntity>> _getDetail() async {
    await Future.delayed(Duration(milliseconds: 400), () async {});
    tenderId = RouteData.of(context).queryParams["tenderId"].stringValue;
    return await ApiHome.getTenderDetail(int.parse(tenderId));
  }

  FutureBuilder<ApiResponse<TenderDetailEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _detailFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<TenderDetailEntity>> snapshot) {
          if (snapshot.hasData) {
            _detailEntity = snapshot.data.result;
            _loadState = LoadState.State_Success;

            return LoadStateLayout(
              bgColor: ThemeColors.colorWhite,
              state: _loadState,
              successWidget: snapshot.data.status != Status.SUCCESS
                  ? _initNoPermissionBody()
                  : _initBody(),
            );
          } else {
            return LoadStateLayout(
              bgColor: ThemeColors.colorWhite,
              state: _loadState,
            );
          }
        });
  }

  /// 分享弹窗
  _showShareBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return ShareBottomSheet(callback: (platform) {
            ShareSdkUtils.share(platform,
                title: "招标新商机",
                content: _detailEntity.title,
                // url: (ApiPath.url_share + "${_detailEntity.id}"),
                url: ApiPath.url_web_down,
                callback: (success, msg) {});
          });
        });
  }

  @override
  void initState() {
    super.initState();
    _detailFuture = _getDetail();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("详情", style: FonStyle.navTextStyle()));
  }

  /// 内容体
  Widget _initBody() {
    /*说明
    ：军队使用fluter_html加载内容 ，因为军队内容只有一张图片
      其他标讯内容使用后端的url方式进行加载，因为涉及到内容有不规则表格时，使用flutter_html无法渲染
    * */
    if (_detailEntity.type == int.parse(AppConstant.TENDERTYPE_ARMY) ||
        _detailEntity.type == int.parse(AppConstant.TENDERTYPE_ARMYWINNING) ||
        _detailEntity.type == int.parse(AppConstant.TENDERTYPE_ARMYDANYI)) {
      return Column(children: [
        Expanded(
            child: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: [_initTitleLayout(), _initContent()],
                ))),
        _initBottomLayout()
      ]);
    }else{
      return Column(
          children: [Expanded(child: _initHtmlContent()), _initBottomLayout()]);
    }
  }

  Widget _initNoPermissionBody() {
    return AbsorbPointer(
        child: Image.asset(
      RPath.imgPath + "img_detail_mask_bg.png",
      fit: BoxFit.fill,
      width: double.infinity,
      height: double.infinity,
    ));
  }

  /// 标讯内 加载的第一种方式
  /// 标题视图
  Widget _initTitleLayout() {
    if (_detailEntity == null) {
      return Container();
    }
    return Container(
        padding: EdgeInsets.all(ScreenAdapter.width(30)),
        width: double.infinity,
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(_detailEntity.title ?? "-",
              maxLines: 2,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(36),
                  fontWeight: FontWeight.bold)),
          SizedBox(height: ScreenAdapter.height(30)),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: _getDesTags(),
          ),
        ]));
  }

//   /// 标讯内容
  Widget _initContent() {
    if (_detailEntity == null) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.all(ScreenAdapter.width(30)),
      child: Column(
        children: <Widget>[
          Row(children: <Widget>[
            Container(
              height: ScreenAdapter.height(24),
              width: ScreenAdapter.width(4),
              margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
              color: ThemeColors.colorType6,
            ),
            Text("公告详情",
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(30),
                    fontWeight: FontWeight.bold))
          ]),
          Html(
            shrinkWrap: true,
            data: _getContentHtml(),
            style: {
              "html": Style(
                  backgroundColor: Colors.white,
                  fontSize: FontSize(ScreenAdapter.sp(30))
//              color: Colors.white,
                  ),
//            "h1": Style(
//              textAlign: TextAlign.center,
//            ),
              "a": Style(textDecoration: TextDecoration.none),
              "table": Style(
                backgroundColor: Color.fromARGB(0x50, 0xee, 0xee, 0xee),
              ),
              "tr": Style(
                border: Border(bottom: BorderSide(color: Colors.grey)),
              ),
              // "th": Style(
              //   padding: EdgeInsets.all(6),
              //   backgroundColor: Colors.grey,
              // ),
              // "td": Style(
              //   padding: EdgeInsets.all(6),
              //   alignment: Alignment.topLeft,
              // ),
              "var": Style(fontFamily: 'serif'),
            },
            onImageError: (dynamic exception, StackTrace stackTrace) {
              print("图片加载异常");
              print(exception);
              print("图片加载异常");
            },
            onLinkTap: (url) {
              // if (RegexUtil.isTel(url)) {
              //   launch("tel:" + url);
              // } else {
              //   ToastUtils.show("无效操作");
              // }
            },
            onImageTap: (src) {
              // print("图片" + src);
              LRouter.navigatorCtx(context).push(Routes.imageBrowsePage,
                  arguments:
                      ImageBrowsePageArguments(images: [src], currentIndex: 0));
            },
          )
        ],
      ),
    );
  }

  /// 标讯内 加载的第二种方式

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'CallPhone',
        onMessageReceived: (JavascriptMessage message) {
          String tel = message.message;
          print("电话号码${tel}");
          launch("tel:" + tel);
          // if (RegexUtil.isMobileExact(tel)) {
          //   launch("tel:" + tel);
          // } else {
          //   ToastUtils.show("无效操作");
          // }
        });
  }

  Widget _initHtmlContent() {
    if (_detailEntity == null) {
      return Container();
    }
    return Container(
        // margin: EdgeInsets.all(ScreenAdapter.width(5)),
        child: WebView(
          onWebViewCreated: (controller){
            Map<String, String> headers = Map();
            headers["Authorization"] = Global.accessToken;
            controller.loadUrl(ApiPath.url_detail + "?id=${_detailEntity.id}",headers: headers);
          },
          javascriptMode: JavascriptMode.unrestricted,
          javascriptChannels: <JavascriptChannel>[
            _toasterJavascriptChannel(context),
          ].toSet(),
          // initialUrl: ,
          onPageFinished: (String value) {
            // webview 页面加载调用
          },
        ));
  }

  Widget _initBottomLayout() {
    return Container(
      decoration: BoxDecoration(
        color: ThemeColors.colorWhite,
        border: Border(
          top: BorderSide(
            width: 0.5, //宽度
            color: ThemeColors.colorType19, //边框颜色
          ),
        ),
      ),
      height: ScreenAdapter.height(100),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: InkWell(
                onTap: () {
                  _setCollection().then((value) => {
                        if (value)
                          {
                            _detailEntity.isFocus = !_detailEntity.isFocus,
                            _collectKey.currentState.update()
                          }
                      });
                },
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      PartRefreshWidget(_collectKey, () {
                        return Image.asset(
                            RPath.imgPath +
                                ((_detailEntity != null
                                        ? _detailEntity.isFocus
                                        : false)
                                    ? "icon_favorites_select.png"
                                    : "icon_detail_collect.png"),
                            width: ScreenAdapter.width(42),
                            height: ScreenAdapter.width(42));
                      }),
                      SizedBox(width: ScreenAdapter.width(10)),
                      Text("收藏")
                    ])),
          ),
          Container(
            width: 1,
            height: 15,
            color: ThemeColors.colorType36,
          ),
          Expanded(
            flex: 1,
            child: InkWell(
                onTap: () {
                  _showShareBottomSheet();
                },
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.share_outlined,
                        color: ThemeColors.colorType14,
                      ),
                      SizedBox(width: ScreenAdapter.width(10)),
                      Text("分享")
                    ])),
          )
        ],
      ),
    );
  }

  List<Widget> _getDesTags() {
    List<Widget> tags = new List<Widget>();
    if (!isEmpty(_detailEntity.province)) {
      tags.add(IconText(
        _detailEntity.province ?? "-",
        icon: Image.asset(RPath.imgPath + "icon_address.png",
            fit: BoxFit.contain,
            width: ScreenAdapter.width(26),
            height: ScreenAdapter.width(26)),
        padding: EdgeInsets.only(right: ScreenAdapter.width(5)),
        style: TextStyle(
          color: ThemeColors.colorType14,
          fontSize: ScreenAdapter.sp(26),
        ),
      ));
    }

    tags.add(IconText(
      "发布时间：" + (_detailEntity.date ?? "-"),
      icon: Image.asset(RPath.imgPath + "icon_time1.png",
          fit: BoxFit.contain,
          width: ScreenAdapter.width(26),
          height: ScreenAdapter.width(26)),
      padding: EdgeInsets.only(right: ScreenAdapter.width(5)),
      style: TextStyle(
        color: ThemeColors.colorType14,
        fontSize: ScreenAdapter.sp(26),
      ),
    ));

    tags.add(IconText(
      (_detailEntity.view.toString() ?? "0") + "人看过",
      icon: Image.asset(RPath.imgPath + "icon_brwse.png",
          fit: BoxFit.contain,
          width: ScreenAdapter.width(26),
          height: ScreenAdapter.width(26)),
      padding: EdgeInsets.only(right: ScreenAdapter.width(5)),
      style: TextStyle(
        color: ThemeColors.colorType14,
        fontSize: ScreenAdapter.sp(26),
      ),
    ));
    return tags;
  }

  String _getContentHtml() {
    String c = """
    <div>${_detailEntity.content ?? ""}</div>
     """;

    // /// 军队的详情内容只是一张图片，不许需要对电话做操作
    // if (_detailEntity.type == int.parse(AppConstant.TENDERTYPE_ARMY) ||
    //     _detailEntity.type == int.parse(AppConstant.TENDERTYPE_ARMYWINNING) ||
    //     _detailEntity.type == int.parse(AppConstant.TENDERTYPE_ARMYDANYI)) {
    //   return c;
    // }
    // List<String> tels = RegexUtil.extractTel(c);
    // for (String t in tels) {
    //   c = c.replaceAll(t, "<a href=$t>$t</a>&nbsp");
    // }
    return c;
  }
}
